package com.example.demo.service;

import com.example.demo.dao.SupplierJpaRepository;
import com.example.demo.entity.Commodity;
import com.example.demo.entity.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class SupplierService {
    @Autowired
    SupplierJpaRepository supplierJpaRepository;

    public Supplier addSupplier(Supplier supplier){return supplierJpaRepository.saveAndFlush(supplier);}

    public Supplier getSupplier(long id){return supplierJpaRepository.getReferenceById(id);}

    public List<Supplier> findSupplier(String name){
        //动态构造查询条件，name和complete不为null时作为条件
        Specification<Supplier> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (name != null) {
                predicateList.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            Predicate[] predicates = predicateList.toArray(new Predicate[predicateList.size()]);
            return criteriaBuilder.and(predicates);
        };

        List<Supplier> result = supplierJpaRepository.findAll(specification);
        return result;
    }

    public void updateSupplier(Supplier supplier){supplierJpaRepository.save(supplier);}

    public void deleteSupplier(long id){supplierJpaRepository.deleteById(id);}

    public void deleteAll(){supplierJpaRepository.deleteAll();}
}
